#!/usr/bin/env python
#-*- coding:utf-8 -*-

from bottle import route
from bottle import redirect
from bottle import template
from bottle import request
from bottle import response
from model.common import  get_shell,encrypt
from model import model
from setting import TEMPLATE


TEMPLATE['BLOG_NAME'] = model.get_option('BLOG_NAME')
TEMPLATE['SUBTITLE'] = model.get_option('SUBTITLE')
TEMPLATE['ADMINMAIL'] = model.get_option('ADMINMAIL')


@route('/login:#/?#')
def login():
    '''
    显示login界面
    '''
    user = request.COOKIES.get('user', '')
    shell = request.COOKIES.get('shell', '')
    if not user and not shell:
        TEMPLATE['login_info'] = False
        return template('login.html', TEMPLATE)
    else:
        redirect('/admin')


# 处理登录提交
@route('/login/post', method="POST")
def login_post():
    '''
    处理登录请求
    '''
    log_data = request.POST
    user = log_data['username']
    passwd = log_data['password']


   
    # 判断用户是否存在
    if model.check_exists(user):
        # 判断密码是否正确
        if model.check_user(user, passwd):
            response.COOKIES['user'] = user
            response.COOKIES['user']['max-age'] = 500
            response.COOKIES['user']['path'] = '/'
            response.COOKIES['shell'] = get_shell(user,passwd)
            response.COOKIES['shell']['max-age'] = 500
            response.COOKIES['shell']['path'] = '/'
            TEMPLATE['user'] = user
            redirect('/admin/')
        else:
            response.COOKIES['user'] = ''
            response.COOKIES['shell'] = ''
            TEMPLATE['login_info'] = '用户名/密码错误,请重新输入'
            return template('login.html', TEMPLATE)
    else:
        TEMPLATE['login_info'] = '用户不存在'
        return template('login.html', TEMPLATE)



#处理登出
@route('/logout')
def logout():
    '''
    处理登出请求,删除COOKIE
    '''
    try:
        response.delete_cookie('user', path='/')
        response.delete_cookie('shell', path='/')
    except:
        pass
    redirect('/')
